import { getUserInfo, login } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

export default {
  namespaced: true,
  state: {
    token: getToken(),
    userInfo: {},
    routes: constantRoutes // 静态路由的数组
  },
  mutations: {
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    removeToken(state) {
      state.token = null
      removeToken()
    },
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    setRoutes(state, newRoutes) {
      state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
    }
  },
  actions: {
    // context上下文，传入参数
    async login(context, data) {
      console.log(data)
      const token = await login(data)
      // 返回一个token 123456
      context.commit('setToken', token)
    },
    async getUserInfo(context) {
      const result = await getUserInfo()
      context.commit('setUserInfo', result)
      return result
    },
    // 退出登录
    logout(context) {
      context.commit('removeToken')// 删除token
      context.commit('setUserInfo', {})// 清空用户信息
      resetRouter()// 重置路由
    }
  }

}
